package com.five.matebook.activity.sync;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.five.filesync.FileUploaderRequest;
import com.five.filesync.MdnsDisovery;
import com.five.filesync.OnNetCallback;
import com.five.matebook.ServerDiscover;
import com.five.matebook.activity.BaseRecordActivity;
import com.five.matebook.activity.MainActivity;
import com.five.matebook.activity.MuliTaskCounting;
import com.five.matebook.activity.config.StroageConfig;
import com.five.matebook.activity.db.DbHelper;
import com.five.matebook.activity.matebook.MateBookManager;
import com.five.matebook.activity.matebook.Matebook;
import com.five.matebook.utils.DateUtils;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

public class DbUploader implements MuliTaskCounting.ICallback {
    private static final String TAG = DbUploader.class.getSimpleName();
    private Context context;
    private ICallback callback;
    public DbUploader(Activity activity, ICallback callback) {
        this.context = activity;
        this.callback = callback;
    }

    private Handler handler = new Handler(Looper.getMainLooper());
    private volatile ProgressDialog dialog;
    private volatile boolean mRunning = false;
    private volatile boolean mNeedShowDlg = false;
    public synchronized boolean startUpload(boolean showProgressBar) {
        return startUpload(showProgressBar, false);
    }

    /**
     * @param showProgressBar 是否显示进度对话框
     * @param forcePush 是否强制推送，不管该matebook是否有更新
     * @return true：同步启动; false: 启动失败，有未完成的任务
     */
    public synchronized boolean startUpload(boolean showProgressBar, boolean forcePush) {
        MateBookManager mateBookManager = StroageConfig.get(context).getMateBookManager();
        synchronized (this) {
            if (mRunning) {
                return false;
            }
            mRunning = true;
            mNeedShowDlg = showProgressBar;
            Log.d(TAG, "startUpload() showDlg=" + mNeedShowDlg);

            if (mNeedShowDlg) {
                dialog = new ProgressDialog(context);
                dialog.setCancelable(false);
                dialog.setMessage("正在查找matebook服务器...");
                dialog.show();
            }

            ServerDiscover.getInstance(context).startDiscover(new MdnsDisovery.OnMdnsCallback() {
                @Override
                public void onServiceDiscoverd(InetAddress addr, int port) {
                    if (dialog != null) {
                        dialog.setMessage("正在push文件到服务器...");
                    }
                    // 上传数据库
                    final MuliTaskCounting counting = new MuliTaskCounting(DbUploader.this);
                    List<FileUploaderRequest> requestList = new ArrayList<>();
                    StroageConfig.get(context).getMateBookManager().trasverLocked((Matebook m) -> {
                        if (m.isMine() && (forcePush || m.getUpdateCount() > 0)) {
                            FileUploaderRequest uploader = new FileUploaderRequest(addr, port, "matebook",
                                    DbHelper.getDbFile(context, m.getFileName()), new OnNetCallback() {
                                @Override
                                public void onResult(boolean susscessed, Object extra) {
                                    counting.addCount(susscessed);
                                }
                            });
                            requestList.add(uploader);
                        }
                    });
                    if (requestList.size() == 0) {
                        // 不需要push
                        return;
                    }
                    counting.setTargetCount(requestList.size());
                    for (FileUploaderRequest request : requestList) {
                        request.execute();
                    }
                    // 后续等待MuliTaskCounting回调
                }

                @Override
                public void onServiceNotFound(String serverName) {
                    finishUpload(false, "上传失败：没有找到Server");
                }
            });
        }
        return true;
    }

    private synchronized void finishUpload(boolean ret, String extraMsg) {
        if (dialog != null) {
            dialog.dismiss();
        }
        if (!TextUtils.isEmpty(extraMsg) && mNeedShowDlg) {
            showAlert(extraMsg);
        }
        mRunning = false;
        if (callback != null) {
            handler.post(() -> {
                callback.onUploadResult(ret);
            });
        }
    }

    @Override
    public void onArriveTarget(int count, boolean ret) {
        String msg = ret ? "数据库同步到服务器成功" : "数据库同步到服务器失败";
        if (ret) {
            StroageConfig.get(context).setHasUpdate(false);
            StroageConfig.get(context).setLastSyncTime(DateUtils.getNowTimeLong());
            StroageConfig.save(context);
        }
        finishUpload(ret, msg);
    }

    protected void showAlert(String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(context)
                        .setTitle("提示")
                        .setMessage(msg)
                        .setCancelable(false)
                        .setPositiveButton("我知道了", null)
                        .show();
            }
        });
    }

    public interface ICallback {
        void onUploadResult(boolean ret);
    }
}
